#include "RightWidget.h"
#include <core/time/time.h>
#include <core/sharedata/login_data.h>
#include <core/Utility.h>
#include <qbprotocol/include/rdProto.h>
#include <qbprotocol/include/SSQBModel.h>
#include <qbprotocol/include/SSMsgStruct.h>
#include <qbtools/message/MessagePoster.h>
#include <uam/UserAccountManager.h>
#include <QStylePainter>
#include <QWindow>
#if WIN32
#include <Windows.h>
#include <winuser.h>
#endif

typedef void (RightWidget::*rightFunc)(void);
struct RightRequest
{
	_eFunID_t		funid;
	rightFunc		func;
	QString			desc;
};

RightRequest rightRequests[] =
{
	{E_FID_QB_USER_PERMISSION_REQ,	&RightWidget::RequestUserPermission, QObject::tr("用户权限(50149)")},
	{E_FID_QB_CSI_AUTHORITY_REQ,	&RightWidget::RequestCSIAuthority, QObject::tr("中证估值权限(50265)")},
	{E_FID_QB_CDC_AUTHORITY_REQ_V2, &RightWidget::RequestCDCAuthority, QObject::tr("估值权限(50340)")},
};

RightWidget::RightWidget(QWidget* parent)
    : BaseWidget(parent)
{
	for (uint32_t i = 0; i < sizeof(rightRequests) / sizeof(RightRequest); i++)
	{
		qbBase::getMessageBond()->RegisterMsgProcessor(rightRequests[i].funid, this);
	}

	setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
	setupUi();
}

RightWidget::~RightWidget()
{
	for (uint32_t i = 0; i < sizeof(rightRequests) / sizeof(RightRequest); i++)
	{
		qbBase::getMessageBond()->UnRegisterMsgProcessor(rightRequests[i].funid, this);
	}
}

void RightWidget::setupUi()
{
	QStringList strList;
	for (uint32_t i = 0; i < sizeof(rightRequests) / sizeof(RightRequest); i++)
	{
		strList.append(rightRequests[i].desc);
	}

	BaseWidget::setupUi(strList);

	connect(btnRequest, &QPushButton::clicked, this, &RightWidget::onBtnRequest);
	connect(btnClear, &QPushButton::clicked, this, &RightWidget::onBtnClear);
	connect(this, &RightWidget::showResult, this, &RightWidget::onShowResult);
}

void RightWidget::onBtnRequest()
{
	if (!loginData::instance().IsLoggedin())
	{
		editor->append(tr("未登录！"));
		return;
	}

	mUserPermission = 0;
	mCDCAuthority = 0;
	mCSIAuthority = 0;
	vctCheck = checkCombo->GetItemCheckStates();
	mTimes = editTimes->text().toInt();

	int nTimeout = editTimeout->text().toInt();
	if (nTimeout <= 0)
	{
		nTimeout = 10;
	}

	int nInterval = editInterval->text().toInt();
	if (nInterval > 0)
	{
		setInterval(nInterval);
		stopIntervalTimer();
		startIntervalTimer();
	}
	else
	{
		for (size_t i = 0; i < vctCheck.size(); i++)
		{
			if (0 == vctCheck[i])
			{
				continue;
			}

			for (int j = 0; j < mTimes; j++)
			{
				(this->*rightRequests[i].func)();
			}
		}
	}

	setTimeout(nTimeout);
	stopTimer();
	startTimer();
}

void RightWidget::onBtnClear()
{
	editor->clear();
}

void RightWidget::RequestUserPermission()
{
	SSRequestMsg Req;
	memset(&Req, 0, sizeof(SSRequestMsg));
	Req.m_MsgType = SSReqType_Message;
	Req.m_FuncID = E_FID_QB_USER_PERMISSION_REQ;

	QBAuthorityQueryReq_t req;
	QBAuthorityQueryReq_t* ptr = &req;
	memset(ptr, 0, sizeof(QBAuthorityQueryReq_t));
	strcpy(ptr->m_UserId, loginData::instance().UserInfo().strUserID.c_str());
	strcpy(ptr->m_CompanyId, loginData::instance().UserInfo().strCompanyId.c_str());
	Req.m_pRequest = (void*)ptr;

	MessagePoster poster(loginData::instance().ConnectID(), &Req, [](qb::proto::Message& msg, qb::SSRequestMsg*) {
		qb::proto::VariantMap submsg;
		submsg.setString("UserId", loginData::instance().UserInfo().strUserID);
		submsg.setString("CompanyId", loginData::instance().UserInfo().strCompanyId);
		msg.SetMap("xQBAuthorityQueryReq", submsg);
		});
	int reqId = poster.send();

	testCase tc;
	tc.idx = ++mUserPermission;
	tc.uBeginTime = GetTickCount();
	mapUserPermission.insert(std::make_pair(reqId, tc));
}

void RightWidget::RequestCDCAuthority()
{
	SSRequestMsg Req;
	memset(&Req, 0, sizeof(SSRequestMsg));
	Req.m_MsgType = SSReqType_Message;
	Req.m_FuncID = E_FID_QB_CDC_AUTHORITY_REQ_V2;

	xCDCAuthorityReq_c req;
	FIELDCOPY(req.m_UserId, loginData::instance().UserInfo().strUserID.c_str());
	FIELDCOPY(req.m_CompanyId, loginData::instance().UserInfo().strCompanyId.c_str());
	Req.m_pRequest = (void*)&req;

	MessagePoster poster(loginData::instance().ConnectID(), &Req, nullptr);
	int reqId = poster.send();

	testCase tc;
	tc.idx = ++mCDCAuthority;
	tc.uBeginTime = GetTickCount();
	mapCDCAuthority.insert(std::make_pair(reqId, tc));
}

void RightWidget::RequestCSIAuthority()
{
	SSRequestMsg Req;
	memset(&Req, 0, sizeof(SSRequestMsg));
	Req.m_MsgType = SSReqType_Message;
	Req.m_FuncID = E_FID_QB_CSI_AUTHORITY_REQ;

	xCSIAuthorityReq_c req;
	Req.m_pRequest = (void*)&req;

	MessagePoster poster(loginData::instance().ConnectID(), &Req, [](qb::proto::Message& msg, qb::SSRequestMsg*) {
		qb::proto::VariantMap submsg;
		submsg.setString("UserId", loginData::instance().UserInfo().strUserID);
		submsg.setString("CompanyId", loginData::instance().UserInfo().strCompanyId);
		msg.SetMap("xCSIAuthorityReq", submsg);
		});
	int reqId = poster.send();

	testCase tc;
	tc.idx = ++mCSIAuthority;
	tc.uBeginTime = GetTickCount();
	mapCSIAuthority.insert(std::make_pair(reqId, tc));
}

void RightWidget::rightRequestFinish(int funcId, long reqId)
{
	emit showResult(funcId, reqId);
}

void RightWidget::printResult(int funcId, int idx, unsigned long useTime, bool bFinish)
{
	QString strShow = QString("%1%2%3:%4 %5:%6ms").arg(tr("收到第")).arg(idx).arg(tr("条")).arg(funcId).arg(tr("耗时")).arg(useTime);
	editor->append(strShow);

	if (bFinish)
	{
		QString strShow = QString("%1:%2%3%4%5 %6%7ms").arg(tr("结果")).arg(funcId).arg(tr("共收到")).arg(mTimes).arg(tr("条返回")).arg(tr("耗时")).arg(useTime);
		editor->append(strShow);
	}
}

void RightWidget::onShowResult(int funcId, long reqId)
{
	int idx = 0;
	unsigned long dwUse = 0;
	unsigned long dwTick = GetTickCount();
	bool bFinish = false;

	if (E_FID_QB_USER_PERMISSION_REQ == funcId)
	{
		std::map<int, testCase>::iterator it = mapUserPermission.find(reqId);
		if (it != mapUserPermission.end())
		{
			idx = it->second.idx;
			dwUse = dwTick - it->second.uBeginTime;
			mapUserPermission.erase(it);

			if (0 == mapUserPermission.size())
			{
				int nInterval = editInterval->text().toInt();
				if (nInterval > 0)
				{
					if (mCurTimes >= mTimes)
					{
						bFinish = true;
					}
				}
				else
				{
					bFinish = true;
				}
			}
		}
		else
		{
			return;
		}
	}
	else if (E_FID_QB_CDC_AUTHORITY_REQ_V2 == funcId)
	{
		std::map<int, testCase>::iterator it = mapCDCAuthority.find(reqId);
		if (it != mapCDCAuthority.end())
		{
			idx = it->second.idx;
			dwUse = dwTick - it->second.uBeginTime;
			mapCDCAuthority.erase(it);

			if (0 == mapCDCAuthority.size())
			{
				int nInterval = editInterval->text().toInt();
				if (nInterval > 0)
				{
					if (mCurTimes >= mTimes)
					{
						bFinish = true;
					}
				}
				else
				{
					bFinish = true;
				}
			}
		}
		else
		{
			return;
		}
	}
	else if (E_FID_QB_CSI_AUTHORITY_REQ == funcId)
	{
		std::map<int, testCase>::iterator it = mapCSIAuthority.find(reqId);
		if (it != mapCSIAuthority.end())
		{
			idx = it->second.idx;
			dwUse = dwTick - it->second.uBeginTime;
			mapCSIAuthority.erase(it);

			if (0 == mapCSIAuthority.size())
			{
				int nInterval = editInterval->text().toInt();
				if (nInterval > 0)
				{
					if (mCurTimes >= mTimes)
					{
						bFinish = true;
					}
				}
				else
				{
					bFinish = true;
				}
			}
		}
		else
		{
			return;
		}
	}
	else
	{
		return;
	}

	printResult(funcId, idx, dwUse, bFinish);
}

void RightWidget::onTimeout()
{
	stopTimer();

	int nRemain1 = (int)mapUserPermission.size();
	int nRemain2 = (int)mapCDCAuthority.size();
	int nRemain3 = (int)mapCSIAuthority.size();

	mapUserPermission.clear();
	mapCDCAuthority.clear();
	mapCSIAuthority.clear();

	if (nRemain1 > 0)
	{
		int funcId = E_FID_QB_USER_PERMISSION_REQ;
		QString strShow = QString("%1:%2%3%4%5 %6%7%8").arg(tr("结果")).arg(funcId).arg(tr("共收到")).arg(mTimes- nRemain1).arg(tr("条返回")).arg(tr("超时")).arg(nRemain1).arg(tr("条"));
		editor->append(strShow);
	}
	if (nRemain2 > 0)
	{
		int funcId = E_FID_QB_CDC_AUTHORITY_REQ_V2;
		QString strShow = QString("%1:%2%3%4%5 %6%7%8").arg(tr("结果")).arg(funcId).arg(tr("共收到")).arg(mTimes - nRemain2).arg(tr("条返回")).arg(tr("超时")).arg(nRemain2).arg(tr("条"));
		editor->append(strShow);
	}
	if (nRemain3 > 0)
	{
		int funcId = E_FID_QB_CSI_AUTHORITY_REQ;
		QString strShow = QString("%1:%2%3%4%5 %6%7%8").arg(tr("结果")).arg(funcId).arg(tr("共收到")).arg(mTimes - nRemain3).arg(tr("条返回")).arg(tr("超时")).arg(nRemain3).arg(tr("条"));
		editor->append(strShow);
	}
}

void RightWidget::onIntervalTimeout()
{
	mCurTimes++;
	if (mCurTimes > mTimes)
	{
		stopIntervalTimer();
		return;
	}

	for (size_t i = 0; i < vctCheck.size(); i++)
	{
		if (0 == vctCheck[i])
		{
			continue;
		}

		(this->*rightRequests[i].func)();
	}
}

STDMETHODIMP_(void) RightWidget::OnResponse(THIS_ int32_t funcId, const SSAckMsg& msg)
{
	if (!msg.m_pRet)
	{
		return;
	}

	if (E_FID_QB_USER_PERMISSION_REQ == funcId)
	{
		xQBUserPermissionAck_c* pdata = (xQBUserPermissionAck_c*)msg.m_pRet;
		SSUserAccountManager& uam = SSUserAccountManager::instance();
		if (strcmp(uam.GetUserInfo().m_UserId, pdata->m_UserId) != 0 || strcmp(uam.GetUserInfo().m_CompanyId, pdata->m_CompanyId) != 0)
		{
			return;
		}

		if (msg.m_IsReceving == 0)
			rightRequestFinish(funcId, msg.m_RequestID);
	}
	else if (E_FID_QB_CDC_AUTHORITY_REQ_V2 == funcId)
	{
		rightRequestFinish(funcId, msg.m_RequestID);
	}
	else if (E_FID_QB_CSI_AUTHORITY_REQ == funcId)
	{
		rightRequestFinish(funcId, msg.m_RequestID);
	}
}

void RightWidget::paintEvent(QPaintEvent* event)
{
    QStylePainter painter(this);
}

void RightWidget::resizeEvent(QResizeEvent* event)
{

}
